<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/webflow.tld" prefix="webflow" %>
<%@ taglib uri="/WEB-INF/webform.tld" prefix="webform" %>

<%@ page import="com.broadvision.ssp.common.SSContext,
                 com.broadvision.data.cache.DataCache" %>
<%@ page import="com.broadvision.ssp.webflow.WebflowHelper" %>
<%@ page import="com.broadvision.data.common.TableData" %>
<%@ page import="com.broadvision.data.client.DataManager" %>
<%@ page import="com.broadvision.data.client.DataCacheUtil" %>

<%@ page import="java.io.IOException" %>
<%@ page import="java.util.StringTokenizer" %>

<%@ page import= "java.util.ArrayList,
  java.util.List,
  java.util.Iterator,
  javax.servlet.jsp.JspWriter,
  com.broadvision.data.client.DataManager,
  com.broadvision.data.client.Content,
  com.broadvision.data.client.QualifierValue,
  com.broadvision.data.client.Qualifier,
  com.broadvision.data.common.DataConstants,
  com.broadvision.data.common.ContentUID"
%>
<%@page import="com.broadvision.ssp.webflow.taglib.*" %>

<%@ include file="./qualifier_common.jsp" %>

<script LANGUAGE="JavaScript" src='<%= response.encodeURL(EncodeTag.encodeURL(request.getContextPath() + "/formJsp/pageflow_utils.js", request)) %>'></script>

<script LANGUAGE="JavaScript">
  var _has_cancel_event = true;

  function doCancel() {
    window.location.href = '<webform:advance event="Cancel"/>';
  }
</script>

<%!

  public static void writeDisplayInfo(String serviceIdStr, String visitorIdStr,
      String contentOidStr, String contentTypeIdStr, List qualifierNameList, 
      JspWriter out, String selections) throws Exception {

    int serviceId = Integer.parseInt(serviceIdStr);
    long visitorId = Long.parseLong(visitorIdStr);
    int contentTypeId = Integer.parseInt(contentTypeIdStr);

    // convert list of interested qualifier names into list of qualifier objects
    List qualifiers = new ArrayList();
    List allQualifiers = Qualifier.getQualifiers(serviceId, 
                DataConstants.BV_ONLINE_DB_CONTENT, visitorId);
                
    for (int i = 0; i < qualifierNameList.size(); i++) {
      for (int j = 0; j < allQualifiers.size(); j++) {
        String name = (String)qualifierNameList.get(i);
        Qualifier qal = (Qualifier)allQualifiers.get(j);
        if (name.equals(qal.getName()))
          qualifiers.add(qal);
      }
    }

    boolean tmpContent = true;
    Content cnt = null;
    
    if( contentOidStr!=null && !contentOidStr.equals("") ) {
      tmpContent = false;
      long contentOid = Long.parseLong(contentOidStr);
      ContentUID uid = new ContentUID(contentTypeId, serviceId, contentOid);
      cnt = new DataManager(visitorId).getContent(uid);
    }

    //get QualifierValue
    Iterator qItr = qualifiers.iterator();

    while (qItr.hasNext()) {
      Qualifier qualifier = (Qualifier) qItr.next();

      //get all online QualifierValue
      List allQVals = qualifier.getQualifierValues(DataConstants.BV_ONLINE_DB_CONTENT);
      if (allQVals.isEmpty())
        continue;

      String selectName;
      selectName = "QualifierAttributes_" + String.valueOf(qualifier.getId() * -1);

      out.println("<TR><TD class=\"label\" width=\"10%\" valign=\"top\">"+qualifier.getName()+":</TD>");
      out.println("<TD valign=\"top\" width=\"90%\" align=\"left\">");

      //selected QualifierValue
      // three options here:
      //   - content OID provided so get the list of selected qualifiers.
      //   - "selections" gives a list of qualifier selections
      //   - no data provided, eg. when creating new content
      long[] selectedIds = null;

      // when the selections are passed in, there is no way to know the length of array
      ArrayList selectedIdsArrayList = new ArrayList();

      if ( !tmpContent ) {
        selectedIds = cnt.getQualifierValueIds(qualifier.getId());
      } 
      else {
        if( selections != null && selections.trim().length() != 0 && 
            !selections.equals("") && !selections.equals("_value3")) {

          // The selections looks like this string:
          //:QualifierAttributes_8257;8461:QualifierAttributes_8254;8447;8446;8445:QualifierAttributes_8252;8434;8439

          long qIdIn = qualifier.getId();
          StringTokenizer tokens = new StringTokenizer(selections, ":");
          while (tokens.hasMoreTokens()) {
            
            String selection = tokens.nextToken();
            StringTokenizer choices = new StringTokenizer(selection, ";");
            
            boolean isQualifier = true;
            long qId = 0;

            while (choices.hasMoreTokens()) {

              if (true == isQualifier) {
                isQualifier = false;
                String selectName2 = choices.nextToken();

                StringTokenizer tmp = new StringTokenizer(selectName2, "_");
                tmp.nextToken();
                qId = -1 * Long.parseLong(tmp.nextToken());
                
              } 
              else {
                long qvId = Long.parseLong(choices.nextToken());
                if (qId == qIdIn)
                  selectedIdsArrayList.add(new Long(qvId) );
              }
            }
          }
        }
      }
    
      if (selectedIds == null && (selectedIdsArrayList.size()==0 )) {
        //selectedIds = new long[0];
        out.println("");
      }
      else {
        out.println("<TABLE>");
        Iterator qvItr = allQVals.iterator();
        while (qvItr.hasNext()) {
          QualifierValue qv = (QualifierValue)qvItr.next();
          long qualValId = qv.getId();

          // check pre-select value 
          // it can either be in selectedIds or selectedIdsArrayList
          if( 0 != selectedIdsArrayList.size() ) {
            if( selectedIdsArrayList.contains(new Long(qualValId)) ) {
              out.println("<TR><TD>");  
              out.print(qv.getName());
              out.print("</TD></TR>");
            }
          }
          else {
            for (int j = 0; j < selectedIds.length; j++) {
              if (qv.getId() == selectedIds[j]) {
                out.println("<TR><TD>");  
                out.print(qv.getName());
                out.print("</TD></TR>");
              }
            }
          }
        } 
        out.println("</TABLE>");
      }
      out.print("</TD></TR>");
        
      // Put some space between list boxes:
      out.print("<TR><TD colspan=2 height=3>&nbsp;</TD></TR>");
    }
    return;
  }

%>

<script language="JavaScript">

  function setFormAction(theForm, eventName, url ) {
    theForm.action = url ;
  }

</script>

<webflow:advance event='next' id='submit-url' />
<webflow:advance event='Cancel' id='cancel-url' />


<form method="post" enctype='' action='<%= (String) pageContext.getAttribute("submit-url") %>' >

  <input type ="hidden" name ="QualifierSelections" value="_value3" >
  <table class="zoneFive" width="100%" cellspacing="0" cellpadding="0" border="0" summary="Main body">
    <tr>
      <td valign="top">
        <div class="pageTitle"><bean:message key="ep.application.qualifiers.view.title"/></div>
        <div class="blockTitle">
          <span class="left">&nbsp;</span>
          <span class="right">&nbsp;</span>
        </div>
    
        <div class="blockWrap">
          <table class="labelForm" width="100%" cellspacing="0" cellpadding="2" summary="Form fields">

<%
  List qualifierNameList = getQualifierList(request.getParameter("QualifierList"));  
  String serviceIdStr = request.getParameter("ServiceId");
  String visitorIdStr = request.getParameter("VisitorId");
  String contentOidStr = request.getParameter("ContentOID");
  String contentTypeIdStr = request.getParameter("ContentTypeId");
  String currModeStr = request.getParameter("CurrMode");
  String selections = request.getParameter("SelectedQualifiers");

  // String selections = ":QualifierAttributes_8257;8461:QualifierAttributes_8254;8447;8446;8445:QualifierAttributes_8252;8434;8439";

  try {
      writeDisplayInfo(serviceIdStr, visitorIdStr, contentOidStr, contentTypeIdStr, qualifierNameList, out, selections);
  }
  catch(Exception e) {
    %><bean:message key="ep.error.qualifiers"/><%
  }
    
  String cancel = "button.cancel";
  String next = "button.continue";
  
  if (currModeStr.equals("NoRelatedItems")) {
    next = "button.done";
  }

%>
          </table>
          <div class="pageButtonWrap" align="right">

          <% if (!currModeStr.equals("NoRelatedItems")) { %>
      <input type="submit" name="Cancel" class="pageButton" value='<bean:message key="<%= cancel %>"/>'  
    onClick="try {if(!_click_form_button(this, this.form)) return false;} catch(e) {};return setFormAction(this.form, 'Cancel', '<%= (String) pageContext.getAttribute("cancel-url") %>')"/>
          <% } %>
       <input type="submit" name="Save" class="pageButton" value='<bean:message key="<%= next %>"/>'
           onClick="try {if(!_click_form_button(this, this.form)) return false;} catch(e) {};return setFormAction(this.form, 'Submit', '<%= (String) pageContext.getAttribute("submit-url") %>')"/>
          </div>
        </div>
      </td>
    </tr>
  </table>  
</form>
